// 草稿页面模块
(function(SEDFramework) {
    'use strict';

    const DraftPageModule = {
        name: 'DraftPage',
        version: '1.0.0',

        // 模块配置
        config: {
            buttonContainer: '.card_right',
            buttons: [
                {
                    id: 'reset-draft',
                    text: '重置草稿',
                    className: 'sed-btn sed-btn-danger',
                    title: '点击重置当前草稿数据',
                    handler: 'handleResetDraft'
                },
                {
                    id: 'debug-panel',
                    text: '接口监听',
                    className: 'sed-btn sed-btn-info',
                    title: '查看接口调用数据',
                    handler: 'handleDebugPanel'
                }
            ]
        },

        // 初始化模块
        init() {
            SEDFramework.log('草稿页面模块初始化', 'info', this.name);
            
            // 检查是否在草稿页面
            if (!SEDFramework.pageDetector.isDraftPage()) {
                SEDFramework.log('不在草稿页面，模块不执行', 'warn', this.name);
                return;
            }

            // 设置DOM观察器
            this.setupObserver();
            
            // 设置路由监听
            this.setupRouteListener();
            
            // 尝试立即添加按钮
            this.tryAddButtons();
        },

        // 设置DOM观察器
        setupObserver() {
            SEDFramework.observer.setup(() => {
                this.tryAddButtons();
            }, this.config.buttonContainer);
        },

        // 设置路由监听
        setupRouteListener() {
            SEDFramework.router.setup(() => {
                if (SEDFramework.pageDetector.isDraftPage()) {
                    this.tryAddButtons();
                }
            });
        },

        // 尝试添加按钮
        tryAddButtons() {
            const container = document.querySelector(this.config.buttonContainer);
            if (container && !container.querySelector('.sed-btn')) {
                this.addButtons(container);
            }
        },

        // 添加按钮
        addButtons(container) {
            this.config.buttons.forEach(buttonConfig => {
                const button = this.createButton(buttonConfig);
                container.appendChild(button);
            });
            
            SEDFramework.log('草稿页面按钮已添加', 'success', this.name);
        },

        // 创建按钮
        createButton(config) {
            const button = document.createElement('button');
            button.id = config.id;
            button.className = config.className;
            button.textContent = config.text;
            button.title = config.title;
            
            button.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this[config.handler](e);
            });
            
            return button;
        },

        // 处理重置草稿
        handleResetDraft(e) {
            const allVars = window.GlobalVarsManager ? window.GlobalVarsManager.getAll() : {};
            
            // 过滤相关参数
            const relevantParams = {};
            for (const [key, value] of Object.entries(allVars)) {
                if (value && value.trim() !== '' && 
                    (key.includes('factory') || key.includes('project') || 
                     key.includes('token') || key.includes('user') || 
                     key.includes('month') || key.includes('year'))) {
                    relevantParams[key] = value;
                }
            }
            
            this.showParamsConfirmDialog(relevantParams, () => {
                this.callResetDraftAPI();
            });
        },

        // 处理调试面板
        handleDebugPanel(e) {
            if (window.APIMonitorLib) {
                const panel = document.getElementById('api-monitor-panel');
                if (panel) {
                    panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
                } else {
                    window.APIMonitorLib.createDebugPanel({
                        title: 'SED接口监控',
                        position: 'top-right'
                    });
                }
            } else {
                alert('API监控库未加载');
            }
        },

        // 显示参数确认对话框
        showParamsConfirmDialog(params, onConfirm) {
            const existingDialog = document.getElementById('params-confirm-dialog');
            if (existingDialog) {
                existingDialog.remove();
            }
            
            const dialog = document.createElement('div');
            dialog.id = 'params-confirm-dialog';
            dialog.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: white;
                border: 2px solid #3742fa;
                border-radius: 8px;
                padding: 20px;
                z-index: 10001;
                max-width: 500px;
                max-height: 80vh;
                overflow-y: auto;
                box-shadow: 0 4px 20px rgba(0,0,0,0.3);
                font-family: Arial, sans-serif;
            `;
            
            let dialogHTML = `
                <h3 style="margin: 0 0 15px 0; color: #3742fa; text-align: center;">重置草稿确认</h3>
                <p style="margin: 0 0 15px 0; color: #ff4757; font-weight: bold;">⚠️ 此操作不可撤销！</p>
            `;
            
            if (Object.keys(params).length > 0) {
                dialogHTML += `
                    <div style="margin-bottom: 15px;">
                        <h4 style="margin: 0 0 10px 0; color: #2f3542;">当前请求参数：</h4>
                        <div style="background: #f8f9fa; padding: 10px; border-radius: 4px; max-height: 200px; overflow-y: auto;">
                `;
                
                for (const [key, value] of Object.entries(params)) {
                    dialogHTML += `
                        <div style="margin-bottom: 5px;">
                            <strong style="color: #3742fa;">${key}:</strong> 
                            <span style="color: #2f3542;">${value}</span>
                        </div>
                    `;
                }
                
                dialogHTML += `
                        </div>
                    </div>
                `;
            } else {
                dialogHTML += `
                    <div style="margin-bottom: 15px; color: #747d8c; text-align: center;">
                        未检测到相关请求参数
                    </div>
                `;
            }
            
            dialogHTML += `
                <div style="text-align: center; margin-top: 20px;">
                    <button id="confirm-reset-btn" style="background: #ff4757; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; margin-right: 10px;">确认重置</button>
                    <button id="cancel-reset-btn" style="background: #747d8c; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">取消</button>
                </div>
            `;
            
            dialog.innerHTML = dialogHTML;
            document.body.appendChild(dialog);
            
            // 绑定事件
            document.getElementById('confirm-reset-btn').addEventListener('click', function() {
                dialog.remove();
                onConfirm();
            });
            
            document.getElementById('cancel-reset-btn').addEventListener('click', function() {
                dialog.remove();
            });
            
            // 点击背景关闭
            dialog.addEventListener('click', function(e) {
                if (e.target === dialog) {
                    dialog.remove();
                }
            });
        },

        // 调用重置草稿API
        callResetDraftAPI() {
            SEDFramework.log('开始调用重置草稿API', 'info', this.name);
            
            const button = document.querySelector('#reset-draft');
            if (button) {
                button.disabled = true;
                button.textContent = '重置中...';
            }

            const baseUrl = window.location.origin;
            const apiUrl = `${baseUrl}/external-api/report-indicator/resetDraft`;

            // 构建请求参数
            const requestData = {};
            
            if (window.GlobalVarsManager) {
                const allVars = window.GlobalVarsManager.getAll();
                const relevantKeys = ['factory_no', 'factory_name', 'sub_factory_no', 'sub_factory_name', 
                                    'user_token', 'current_project', 'month_str'];
                
                for (const key of relevantKeys) {
                    if (allVars[key] && allVars[key].trim() !== '') {
                        requestData[key] = allVars[key];
                    }
                }
            }
            
            SEDFramework.log(`API请求参数: ${JSON.stringify(requestData)}`, 'info', this.name);

            GM_xmlhttpRequest({
                method: 'POST',
                url: apiUrl,
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                data: JSON.stringify(requestData),
                onload: (response) => {
                    if (button) {
                        button.disabled = false;
                        button.textContent = '重置草稿';
                    }

                    if (response.status === 200) {
                        try {
                            const result = JSON.parse(response.responseText);
                            if (result.success) {
                                SEDFramework.log('草稿重置成功', 'success', this.name);
                                alert('草稿重置成功！');
                            } else {
                                SEDFramework.log(`重置失败: ${result.message || '未知错误'}`, 'error', this.name);
                                alert('重置失败：' + (result.message || '未知错误'));
                            }
                        } catch (e) {
                            SEDFramework.log(`响应解析失败: ${e.message}`, 'error', this.name);
                            alert('响应解析失败：' + e.message);
                        }
                    } else {
                        SEDFramework.log(`请求失败，状态码: ${response.status}`, 'error', this.name);
                        alert('请求失败，状态码：' + response.status);
                    }
                },
                onerror: (error) => {
                    SEDFramework.log(`网络请求失败: ${error.message}`, 'error', this.name);
                    if (button) {
                        button.disabled = false;
                        button.textContent = '重置草稿';
                    }
                    alert('网络请求失败：' + error.message);
                }
            });
        }
    };

    // 注册模块
    SEDFramework.moduleManager.register('DraftPage', DraftPageModule);
    
    // 自动初始化
    if (SEDFramework.pageDetector.isDraftPage()) {
        DraftPageModule.init();
    }

    return DraftPageModule;
})(window.SEDFramework); 